import storage from '@/utils/storage'
import { login, logout } from '@/api/login'
import { getUserInfo } from '@/api/user'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import store from '@/store/index'

const user = {
  state: {
    token: '',
    name: '',
    avatar: '',
    userPermissions: [],
    info: {}
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, nickname) => {
      state.nickname = nickname
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_PERMISSIONS: (state, userPermissions) => {
      state.userPermissions = userPermissions
      window.__USER_PERMISSIONS__ = userPermissions
    },
    SET_INFO: (state, info) => {
      state.info = info
    }
  },

  actions: {
    // 登录
    Login ({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo).then(data => {
          const {accessToken} = data
          storage.set(ACCESS_TOKEN, accessToken, +new Date() + 30 * 24 * 60 * 60 * 1000)
          commit('SET_TOKEN', accessToken)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    getUserInfo ({ commit }) {
      let data={
        nickName:'超级管理员',
        thumbnailPath:'',
        permissionIds:['personal'],
        
      }
      commit('SET_INFO', data)
      commit('SET_NAME', data.nickName)
      commit('SET_AVATAR', data.thumbnailPath)
      commit('SET_PERMISSIONS', data.permissionIds)
      return
      console.log('1115')
      return new Promise((resolve, reject) => {
        getUserInfo({id:1026}).then(data => {
          data.permissionIds=['menu']
          commit('SET_INFO', data)
          commit('SET_NAME', data.nickName)
          commit('SET_AVATAR', data.thumbnailPath)
          commit('SET_PERMISSIONS', data.permissionIds)
          resolve(data.permissionIds)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    Logout ({ commit, state }) {
      return new Promise((resolve) => {
        // logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_INFO', {})
          commit('SET_PERMISSIONS', [])
          storage.remove(ACCESS_TOKEN)
          storage.remove('dictList')
          resolve()
        // }).catch(() => {
        //   resolve()
        // }).finally(() => {
        // })
      })
    }

  }
}

export default user
